import { ProColumns, ProTable } from '@/components/Pro';
import {
  dateFormatterMap,
  initialDateMap,
  selectTypeMap,
} from '@/pages/Statistics/Income/components/CommonMap';
import {
  statisticIncomeV2ControllerEsRevenueDayReportList as getDayList,
  statisticIncomeV2ControllerEsRevenueMonthReportList as getMonthList,
  statisticIncomeV2ControllerEsRevenueYearReportList as getYearList,
} from '@/services/ess/statisticIncomeV2';
import { getDeviceCascader } from '@/utils/formatterTree';
import { useModel } from '@@/exports';
import { useIntl } from '@umijs/max';
import dayjs from 'dayjs';
import _ from 'lodash';
import moment from 'moment';
import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import './Common.less';

const stationAreaId = 'root';

type IProps = {
  dateType: string;
};

type areaColumnsType = {
  title: string;
  dataIndex: string;
  key: string;
  // 汇总数据key
  totalKey: string;
  hideInSearch: boolean;
};

const requestMap = {
  day: getDayList,
  month: getMonthList,
  year: getYearList,
};

const IncomeList: React.FC<IProps> = ({ dateType }, ref) => {
  const intl = useIntl();
  const tableRef = useRef(null);
  const formRef = useRef(null);

  const { initialState } = useModel('@@initialState');
  // 分区维度
  const [deviceTree, setDeviceTree] = useState();
  const [totalData, setTotalData] = useState({});
  const [visibleColumnValues, setVisibleColumnValues] = useState([]);

  const handleArea = (value) => {
    let tempTreeData = _.cloneDeep(deviceTree);
    tempTreeData?.map((item) => {
      if (!value?.length || !value) {
        item.disabled = false;
        item?.subDevices?.map((areaItem) => {
          areaItem.disabled = false;
          return areaItem;
        });
      } else if (value?.includes(stationAreaId)) {
        item.disabled = false;
        item?.subDevices?.map((areaItem) => {
          areaItem.disabled = true;
          return areaItem;
        });
      } else {
        item.disabled = true;
        item?.subDevices?.map((areaItem) => {
          areaItem.disabled = false;
          return areaItem;
        });
      }
      return item;
    });
    setDeviceTree(tempTreeData);
  };

  // 左侧固定列
  const tableColumns: ProColumns[] = [
    {
      title: intl.formatMessage({ id: 'statistics.income.select' }),
      dataIndex: 'datePicker',
      initialValue: initialDateMap.get(dateType),
      valueType: selectTypeMap.get(dateType),
      fieldProps: {
        allowClear: false,
        disabledDate: (current) => {
          return current && current > moment().endOf('month');
        },
      },
      search: {
        transform: (value) => {
          return {
            startDate: dayjs(value[0]).format(dateFormatterMap.get(dateType)),
            endDate: dayjs(value[1]).format(dateFormatterMap.get(dateType)),
          };
        },
      },
      hideInTable: true,
      key: 'datePicker',
    },
    // 分区维度模块
    {
      title: intl.formatMessage({ id: 'statistics.work.dimensions' }),
      dataIndex: 'areaIdList',
      hideInTable: true,
      valueType: 'treeSelect',
      initialValue: [stationAreaId],
      fieldProps: {
        treeData: deviceTree,
        fieldNames: {
          label: 'deviceName',
          value: 'areaId',
          children: 'subDevices',
        },
        multiple: true,
        maxTagCount: 'responsive',
        showSearch: true,
        treeNodeFilterProp: 'name',
        maxCount: 100,
        onChange: (value) => {
          handleArea(value);
        },
      },
      hideInSearch: !initialState?.isArea,
      key: 'areaIdList',
    },
    {
      title: intl.formatMessage({ id: 'batteryVoltage.no' }),
      valueType: 'index',
      dataIndex: 'index',
      hideInSearch: true,
      width: 80,
      key: 'index',
    },
    {
      title: intl.formatMessage({ id: 'statistics.common.period' }),
      dataIndex: 'date',
      key: 'date',
      hideInSearch: true,
    },
  ];
  const revenueUnit = intl.formatMessage({ id: 'electricityPrice.revenueUnit' });
  // 动态列模板
  const stationColumns: areaColumnsType[] = [
    {
      title: `${intl.formatMessage({
        id: 'electricityPrice.energyStorageSischargeRevenue',
      })}${revenueUnit}`,
      dataIndex: 'totalIncome',
      key: 'totalIncome',
      hideInSearch: true,
      totalKey: 'esTotalIncome',
    },
    {
      title: `${intl.formatMessage({
        id: 'electricityPrice.sharpPeriodDischargeIncome',
      })}${revenueUnit}`,
      dataIndex: 'apicalIncome',
      key: 'apicalIncome',
      hideInSearch: true,
      totalKey: 'esTotalApicalIncome',
    },
    {
      title: `${intl.formatMessage({
        id: 'electricityPrice.peakPeriodDischargeIncome',
      })}${revenueUnit}`,
      dataIndex: 'peakIncome',
      key: 'peakIncome',
      hideInSearch: true,
      totalKey: 'esTotalPeakIncome',
    },
    {
      title: `${intl.formatMessage({
        id: 'electricityPrice.regularDischargeIncome',
      })}${revenueUnit}`,
      dataIndex: 'flatIncome',
      key: 'flatIncome',
      hideInSearch: true,
      totalKey: 'esTotalFlatIncome',
    },
    {
      title: `${intl.formatMessage({
        id: 'electricityPrice.dischargeIncomeDuringValleyPeriods',
      })}${revenueUnit}`,
      dataIndex: 'segmentIncome',
      key: 'segmentIncome',
      hideInSearch: true,
      totalKey: 'esTotalSegmentIncome',
    },
    {
      title: `${intl.formatMessage({
        id: 'electricityPrice.peakSegmenOnGridElectricityConsumption',
      })}(kWh)`,
      dataIndex: 'apicalPocOnGridEnergy',
      key: 'apicalPocOnGridEnergy',
      hideInSearch: true,
      totalKey: 'esTotalApicalPocOnGridEnergy',
    },
    {
      title: `${intl.formatMessage({
        id: 'electricityPrice.peakOnGridElectricityConsumption',
      })}(kWh)`,
      dataIndex: 'peakPocOnGridEnergy',
      key: 'peakPocOnGridEnergy',
      hideInSearch: true,
      totalKey: 'esTotalPeakPocOnGridEnergy',
    },
    {
      title: `${intl.formatMessage({
        id: 'electricityPrice.flatGridElectricityConsumption',
      })}(kWh)`,
      dataIndex: 'flatPocOnGridEnergy',
      key: 'flatPocOnGridEnergy',
      hideInSearch: true,
      totalKey: 'esTotalFlatPocOnGridEnergy',
    },
    {
      title: `${intl.formatMessage({
        id: 'electricityPrice.segmentOnGridElectricityConsumption',
      })}(kWh)`,
      dataIndex: 'segmentPocOnGridEnergy',
      key: 'segmentPocOnGridEnergy',
      hideInSearch: true,
      totalKey: 'esTotalSegmentPocOnGridEnergy',
    },
    {
      title: `${intl.formatMessage({
        id: 'electricityPrice.sharpDischargeElectricityDuringPeakHours',
      })}(kWh)`,
      dataIndex: 'apicalDischargeCapacity',
      key: 'apicalDischargeCapacity',
      hideInSearch: true,
      totalKey: 'esTotalApicalDischarge',
    },
    {
      title: `${intl.formatMessage({ id: 'electricityPrice.peakDischarge' })}(kWh)`,
      dataIndex: 'peakDischargeCapacity',
      key: 'peakDischargeCapacity',
      hideInSearch: true,
      totalKey: 'esTotalPeakDischarge',
    },
    {
      title: `${intl.formatMessage({ id: 'electricityPrice.regularDischargeCapacity' })}(kWh)`,
      dataIndex: 'flatDischargeCapacity',
      key: 'flatDischargeCapacity',
      hideInSearch: true,
      totalKey: 'esTotalFlatDischarge',
    },
    {
      title: `${intl.formatMessage({
        id: 'electricityPrice.dischargeElectricityDuringValleyPeriods',
      })}(kWh)`,
      dataIndex: 'segmentDischargeCapacity',
      key: 'segmentDischargeCapacity',
      hideInSearch: true,
      totalKey: 'esTotalSegmentDischarge',
    },
  ];
  // 动态列
  const [additionalColumns, setAdditionalColumns] = useState(stationColumns);

  useEffect(() => {
    if (initialState?.isArea) {
      // 获取分区信息
      getDeviceCascader(false, 2).then((res) => {
        setDeviceTree(
          (res ?? [])?.map((item) => {
            if (item?.nodeType === 'ROOT') {
              item.areaId = stationAreaId;
              item.disabled = false;
              item?.subDevices?.map((areaItem) => {
                areaItem.disabled = true;
                return areaItem;
              });
            }
            return item;
          }),
        );
      });
    }
  }, []);

  useImperativeHandle(ref, () => ({
    getSearchValues: () => {
      const formValues = formRef?.current?.getFieldFormatValue() ?? {};
      return {
        ...formValues,
        areaIdList: formValues?.areaIdList?.includes(stationAreaId)
          ? undefined
          : formValues?.areaIdList,
        unit: dateType,
        reportType: 'ES_REVENUE',
      };
    },
  }));

  // 汇总行
  const renderSummary = () => {
    if (totalData?.isTableDataEmpty) {
      return (
        <ProTable.Summary.Row>
          {visibleColumnValues['index']?.show !== false && (
            <ProTable.Summary.Cell
              index={visibleColumnValues['index']?.order}
            ></ProTable.Summary.Cell>
          )}
          {visibleColumnValues['date']?.show !== false && (
            <ProTable.Summary.Cell index={visibleColumnValues['date']?.order}>
              {intl.formatMessage({ id: 'electricityPrice.cumulativestatistics' })}
            </ProTable.Summary.Cell>
          )}
          {_.cloneDeep(additionalColumns)?.map(
            (item) =>
              visibleColumnValues[item.key]?.show !== false && (
                <ProTable.Summary.Cell index={visibleColumnValues[item.key]?.order} key={item.key}>
                  {totalData[item.totalKey]}
                </ProTable.Summary.Cell>
              ),
          )}
        </ProTable.Summary.Row>
      );
    }
  };
  return (
    <>
      <ProTable
        headerTitle=" "
        rowKey={'reportId'}
        columns={[...tableColumns, ...additionalColumns]}
        actionRef={tableRef}
        formRef={formRef}
        onReset={async () => {
          tableRef?.current?.reloadAndRest();
          handleArea([stationAreaId]);
        }}
        request={async (params) => {
          const pageSize = Number(params.pageSize);
          // 是否查询分区
          let areaQuery = true;
          // 分区个数
          let areaLen = 1;
          if (
            params?.areaIdList?.includes(stationAreaId) ||
            !params?.areaIdList ||
            !params?.areaIdList?.length
          ) {
            // 整站查询
            params.areaIdList = null;
            areaQuery = false;
          } else {
            // 分区查询
            areaLen = params?.areaIdList?.length || 1;
          }
          let tempColumns = [];
          if (areaQuery) {
            // 构建分区表头列配置
            params?.areaIdList?.forEach((areaId) => {
              const arr = _.cloneDeep(stationColumns)?.map((item) => {
                item.dataIndex = `${areaId}_${item.dataIndex}`;
                item.title = `${
                  deviceTree?.[0]?.subDevices?.find((device) => device?.areaId === areaId)
                    ?.deviceName
                }_${item.title}`;
                item.key = `${areaId}_${item.key}`;
                item.totalKey = `${areaId}_${item.totalKey}`;
                return item;
              });
              tempColumns.push(...arr);
            });
          } else {
            tempColumns = _.cloneDeep(stationColumns);
          }
          setAdditionalColumns(tempColumns);

          params.pageSize = pageSize * areaLen;
          const res = await requestMap[dateType](params);
          const data = res?.data;
          const pageData = data?.page ?? [];

          // 处理汇总数据
          let summaryData = {
            //表格是否有数据
            isTableDataEmpty: Boolean(data?.summaryRevenueVos?.length),
          };
          data?.summaryRevenueVos?.forEach((item) => {
            stationColumns.forEach((aItem) => {
              const tData = item[aItem.totalKey];
              if (item?.areaId) {
                summaryData[`${item.areaId}_${aItem.totalKey}`] = tData;
              } else {
                summaryData[`${aItem.totalKey}`] = tData;
              }
            });
          });
          setTotalData(summaryData);

          // 处理表格数据
          if (areaQuery) {
            let recordData = [];
            pageData?.records?.forEach((item) => {
              let obj = {};
              stationColumns.forEach((aItem) => {
                obj[`${item?.areaId}_${aItem.dataIndex}`] = item[aItem.dataIndex];
              });
              let rowIndex = recordData.findIndex(
                (recordItem) => recordItem.reportId === item.reportId,
              );
              if (rowIndex > -1) {
                const tempObj = {
                  ...recordData[rowIndex],
                  ...obj,
                };
                recordData[rowIndex] = tempObj;
              } else {
                recordData.push({
                  ...item,
                  ...obj,
                });
              }
            });

            return {
              ...res,
              data: recordData,
              pageSize: pageSize,
              total: Number(pageData?.total) / areaLen,
            };
          } else {
            return {
              ...res,
              data: pageData,
            };
          }
        }}
        search={{
          className: 'searchPosInline',
        }}
        columnsState={{
          onChange: (values) => {
            setVisibleColumnValues(values);
          },
        }}
        summary={() => renderSummary()}
        toolbar={{
          className: 'toobalrZindex',
          actions: [
            // eslint-disable-next-line react/button-has-type
          ],
        }}
      ></ProTable>
    </>
  );
};

export default forwardRef(IncomeList);
